package com.example.video.service;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.example.video.config.OSSConfig;
import com.example.video.service.inter.IFileService;
import com.example.video.vo.PostPolicyVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.util.Date;

@Slf4j
@Service
public class FileServiceImpl implements IFileService {

    private final OSSConfig ossConfig;

    @Autowired
    public FileServiceImpl(OSSConfig ossConfig) {
        this.ossConfig = ossConfig;
    }

    @Override
    public PostPolicyVo getPostObjectPolicy(String filePath) {
        //有效期一个小时
        long expireEndTime = System.currentTimeMillis() + 60 * 1000;
        Date expiration = new Date(expireEndTime);
        PolicyConditions policyConds = new PolicyConditions();
        policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
        policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, filePath);
        OSSClient ossClient = new OSSClient(ossConfig.getEndpoint(), ossConfig.getAccessKeyId(), ossConfig.getAccessKeySecret());
        String postPolicy = ossClient.generatePostPolicy(expiration, policyConds);
        byte[] binaryData;
        binaryData = postPolicy.getBytes(StandardCharsets.UTF_8);
        String encodedPolicy = BinaryUtil.toBase64String(binaryData);
        String postSignature = ossClient.calculatePostSignature(postPolicy);

        PostPolicyVo policy = new PostPolicyVo();
        policy.setAccessId(ossConfig.getAccessKeyId());
        policy.setHost("https://" + ossConfig.getBucketName() + "." + ossConfig.getEndpoint());
        policy.setDir(filePath);
        policy.setExpire(String.valueOf(expireEndTime / 1000));
        policy.setPolicy(encodedPolicy);
        policy.setSignature(postSignature);
        return policy;
    }

}
